<template>
    <view class="pay-status-main">
        <view class="pay-status-content">
            <view class="status">
                <view v-if="payType == 0">
                    <uni-load-more iconType="auto" status="loading" color="" :iconSize="54" :showText="false" />
                    <view class="status-text">支付中</view>
                </view>
                <view v-else-if="payType == 1">
                    <image :src="getImgOssUrl('/ui-prod-2.0.0/icon_pay_success_1.2.png')"></image>
                    <view class="status-text">支付成功</view>
                </view>
                <view v-else>
                    <image :src="getImgOssUrl('/ui-prod-2.0.0/icon_pay_fail_1.2.png')"></image>
                    <view class="status-text">支付失败</view>
                </view>
            </view>
            <view class="buttons">
                <view class="home-button" @click="toHome"> 返回首页 </view>
                <view
                    v-if="[3, 4, 5].includes(Number(orderType)) && payType == 1 && Data.spellOrderId"
                    class="detail-button"
                    @click="toGroupDetail">
                    查看拼团详情
                </view>
                <view v-else-if="![3, 4, 5].includes(Number(orderType))" class="detail-button" @click="toDetail">
                    查看订单
                </view>
            </view>
        </view>
        <Decorate :datas="options" />
        <MessageBox ref="messagebox" btnName="关闭" :content="dialog.content" @comfirm="cancelConfirm"></MessageBox>
    </view>
</template>
<script setup>
import Decorate from '@/components/decorate';
import { ref, reactive, onMounted } from 'vue';
import router from '@/router';
import storage from '@/commons/storage';
import { getParamsBySceneHook } from '@/hooks';
import { getImgOssUrl, floatDivide, isNotEmpty } from '@/commons/utils.js';
import subscribe from '@/commons/subscribe';
import request from '@/request';
import MessageBox from '@/components/messageBox';
const messagebox = ref();
const props = defineProps({
    orderId: {
        type: [String, Number],
        default: ''
    },
    // 付款状态 0支付中 1支付成功 2 支付失败
    type: {
        type: [String, Number],
        default: 0
    },
    orderType: {
        type: [String, Number],
        default: 1
    },

    scene: {
        type: String,
        default: ''
    }
    // 已废弃
    // spellOrderId: {
    //     type: [String, Number]
    // }
});

const Data = reactive({
    spellOrderId: ''
});

const dialog = reactive({
    content: ''
});
const options = reactive({ data: {}, shareImg: '', shareTitle: '' });

const payType = ref(props.type);

const toDetail = () => {
    if (props.scene) {
        // 通过生成二维码需要跳转到订单列表
        router.redirectTo({
            url: `/pages-user/orderlist/index?status=0`
        });
    } else {
        router.redirectTo({
            url: `/pages-user/orderdetail/index?orderId=${props.orderId}`
        });
    }
};
const toGroupDetail = async () => {
    await subscribe('collection_detail');
    router.push({
        path: '/pages-cart/group/index',
        query: {
            spellOrderId: Data.spellOrderId,
            from: 'paystatus'
        }
    });
};

const toHome = () => {
    router.switchTab({
        url: '/pages/tabbar/home'
    });
};
// 转换优惠券内容
const couponContent = obj => {
    const { couponPrerequisites, couponMatch, couponPrerequisitesAdditional, couponDiscountContent } = obj;
    const pre = [
        '无门槛，',
        `满${floatDivide(couponPrerequisitesAdditional, 100)}元，`,
        `满${couponPrerequisitesAdditional}件，`
    ];
    const num = [`全部商品`, `部分商品`, '部分商品'];
    return (pre[couponPrerequisites - 1] || '') + (num[couponMatch - 1] || '');
};
const querySettingInfo = async () => {
    const { data } = await request('payResultInfoServ');
    if (Object.keys(data).length && data.components) {
        let getData = JSON.parse(JSON.stringify(options.data));
        Object.assign(getData, data);
        options.shareImg = getData.shareImg;
        options.shareTitle = getData.shareTitle;
        let productIds = [];
        let seckillIds = [];
        let groupbuyIds = [];
        let couponIds = [];
        let components = getData.components;
        components.forEach(async (item, index) => {
            if (item.component.name == 'PlaceHolderView') {
                components.splice(index, 1);
                return;
            }
            if (item.component.name == 'product') {
                productIds = [...productIds, ...item.options.imgList];
            } else if (item.component.name == 'seckill') {
                seckillIds = [...seckillIds, ...item.options.imgList];
            } else if (item.component.name == 'groupbuy') {
                if (item.options.addType == 1) {
                    groupbuyIds = [...groupbuyIds, ...item.options.imgList];
                }
            } else if (item.component.name == 'coupon') {
                // 获取优惠券id数组
                couponIds = [...couponIds, ...item.options.imgList];
            }
        });
        let productData = [];
        let seckillData = [];
        let groupData = [];
        let couponData = [];
        if (couponIds.length) {
            couponData = await request('couponList', { couponIds: couponIds, userId: storage.get('userId') });
        }
        if (productIds.length) {
            productData = await request('goodsList', { goodsId: productIds });
        }
        if (seckillIds.length) {
            seckillData = await request('seckillList', { activityId: seckillIds });
        }
        if (groupbuyIds.length) {
            groupData = await request('seckillListManual', { activityId: groupbuyIds });
        }
        let param = await Promise.all(
            components.map(async item => {
                const name = item.component.name;
                const imgLists = {
                    product: isNotEmpty(productData?.data) ? productData?.data : [],
                    seckill: isNotEmpty(seckillData?.data) ? seckillData?.data : [],
                    groupbuy: isNotEmpty(groupData?.data) ? groupData?.data : [],
                    coupon: isNotEmpty(couponData?.data) ? couponData?.data : []
                };
                if (name == 'product' || name == 'seckill') {
                    item.options.imgList.forEach((id, indexs) => {
                        let proItem = imgLists[name].filter(val => val.id == id);
                        if (proItem.length) {
                            item.options.imgList[indexs] = proItem[0];
                        } else {
                            item.options.imgList[indexs] = null;
                        }
                    });
                }
                //获取优惠券对应id的实时数据
                if (name == 'coupon') {
                    item.options.imgList.forEach((id, indexs) => {
                        let proItem = imgLists[name].filter(val => val.id == id);
                        if (proItem.length) {
                            item.options.imgList[indexs] = proItem.map(
                                ({ couponAcquiredNumber, id, couponId, couponInfo }) => {
                                    const item = {
                                        ...couponInfo
                                    };
                                    // receiveStatus:1表示已领完 2表示领取已达上限
                                    item.receiveStatus =
                                        item.couponTotal - couponAcquiredNumber == 0
                                            ? 1
                                            : item?.acquireLimit
                                            ? '2'
                                            : '';
                                    item.content = couponContent(item);
                                    item.id = id;
                                    item.couponId = couponId;

                                    return item;
                                }
                            )[0];
                        } else {
                            item.options.imgList[indexs] = null;
                        }
                    });
                }
                if (name == 'groupbuy') {
                    if (item.options.addType == 1) {
                        item.options.imgList.forEach((id, indexs) => {
                            let proItem = imgLists[name].filter(val => val.id == id);
                            if (proItem.length) {
                                item.options.imgList[indexs] = proItem[0];
                            } else {
                                item.options.imgList[indexs] = null;
                            }
                        });
                    } else {
                        let typeList = ['have_group_goods_num', 'activity_end_time', 'activity_start_time'];
                        const groupAuto = await request('groupList', {
                            autogather: 1,
                            direction: 'desc',
                            activityType: item.options.groupType,
                            reorder: typeList[item.options.rule - 1]
                        });
                        item.options.imgList = isNotEmpty(groupAuto?.data) ? groupAuto?.data : [];
                    }
                }
                return item;
            })
        );
        // 过滤删除商品，当选择商品全部删除后，删除组件不再显示
        options.data.components = param
            .map(item => {
                item.options.imgList = item?.options?.imgList?.filter(fItem => fItem);
                return item;
            })
            .filter(item => !item.options.imgList || item.options?.imgList.length > 0);
    } else {
        Object.assign(options, { data: {}, shareImg: '', shareTitle: '' });
    }
};

const cancelConfirm = () => {
    messagebox?.value?.closePopup();
};

const checkOrderStatus = () => {
    // 判断errcode是不是为空 不为空直接弹errMsg
    request('orderQueryServ', { orderId: props.orderId }).then(res => {
        if (res.data[0]?.errCode) {
            dialog.content = res.data[0]?.errMsg;
            messagebox.value.openPopup();
            payType.value = 1;
        } else {
            Data.spellOrderId = res.data[0]?.spellOrderId;
            payType.value = 1;
        }
    });
};

onMounted(async () => {
    if (props.scene) {
        // 分享弹窗生成的二维码跳转的
        const res = await getParamsBySceneHook(props.scene, 1);
        payType.value = res.type;
    } else if (!props.type) {
        payType.value = 0;
        let timeId = setInterval(() => {
            checkOrderStatus();
            clearInterval(timeId);
        }, 3000);
    } else if ([3, 4, 5].includes(Number(props.orderType))) {
        // 0元付拼团订单需要查一下spellOrderId
        checkOrderStatus();
    }
    querySettingInfo();
});
</script>
<style lang="scss" scoped>
.pay-status-main {
    background: #f8f8f8;
    :deep(.uni-load-more__text) {
        display: none;
    }
    .pay-status-content {
        margin-top: 18rpx;
        padding: 0 29rpx 72rpx;
        background: #ffffff;
        text-align: center;
        font-size: 29rpx;
        .status {
            padding-top: 112rpx;
            image {
                width: 109rpx;
                height: 109rpx;
            }
            .status-text {
                padding-top: 29rpx;
            }
        }
        .buttons {
            margin-top: 85rpx;
            display: flex;
            justify-content: space-around;
            .detail-button {
                height: 80rpx;
                line-height: 80rpx;
                background: linear-gradient(270deg, #ff5356 0%, #fe292b 100%);
                border-radius: 36rpx;
                color: #ffffff;
                width: 300rpx;
            }
            .home-button {
                height: 80rpx;
                line-height: 80rpx;
                border-radius: 36rpx;
                border: 2rpx solid #cccccc;
                width: 300rpx;
            }
        }
    }
}
</style>
